'use strict';

angular.module('afasApp')
  .controller('RoomsCtrl', ['$scope', 'Services', '$state', function ($scope, Services, $state) {

    $scope.rooms = [];
    $scope.roomNew = {};
    $scope.params = {
      keyword: $scope.searchText
    };
    $scope.errors = {};

    // PAGINATION
    $scope.pagesize = 10;

    $scope.pagination = {
      current: 1
    };

    $scope.pageChanged = function(newPage) {
      getResultsPage(newPage);
    };

    function getResultsPage(pageNumber) {
      var data = $scope.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.pagination.current = pageNumber;
      Services.getItems('classrooms', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.totalItems = pagingData.TotalCount;
        $scope.rooms = results.data;
      });
    }
    getResultsPage(1);

    $scope.addRoom = function () {
      $scope.errors = {};
      Services.add('classrooms', $scope.roomNew)
      .then(function(results){
        console.log(results);
        $scope.roomNew = {};
        $state.go( '^.list' );
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };

    $scope.deleteRoom = function (room) {
      Services.delete('classrooms', room)
      .then(function(){
        loadRemoteData();
      });
    };
  }]).controller('RoomCtrl', ['$scope', 'Services', '$state', '$stateParams', function ($scope, Services, $state, $stateParams) {

    $scope.currentRoom = {};
    $scope.currentID = $stateParams.id;
    Services.getItem('classrooms', $scope.currentID)
    .then(function(results){
      $scope.currentRoom = results.data;
    });

    $scope.updateRoom = function () {
      Services.update('classrooms', $scope.currentRoom, $scope.currentID)
      .then(function(results){
        console.log(results);
        $state.go( '^.show', {id: $scope.currentID} );
      });
    };
  }]);